// pages/home/home.js
var AccessToken = "4A008AD8B0740D2B79987312A8B4D3E324A47117C0C5BB54D589EE4EC401B8D70F01CA0A578C0E0EEF5C144DD9AA74B695EB0D869C92AC21FDD7C842843504034EEDC7E9FF284D2B4798FAA46008E0AA2767705B3C42EE1DD5121F15C2A836D43C81F0D1BEC85AB703B485A84EA5F333827A84961ABE629A9359F6F63EDE3ACE884FB3E826BDB0EA2B76549C5784A9F06837316EBAF22BF5FD77C2BC5CA0135BD3F1786C1BDDDDC06DB2D3B20CC6515FF9CA8494E400D2358739363D941F981B3CD4639C30050BE463FEC0675C4DA90878334BF7040ED2D083B355D18D2A5495"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    currentTab: 0,
    onLine: false,
    temp: '',
    hum: '',
    light: '',
    fire: '',
    temp_danwei: '',
    hum_danwei: '',
    light_danwei: '',
    livingLightState: 0,
    roomLightState: 0,
    livingFanState: 0,
    roomFanState: 0,
    addressIP: '',
    doorBig: 0, 
    doorCar: 0, 
    tieleFlex: 0,
    titleFlex2: 0,
    isControlling: false,
    hasLoadedStaticData: false 
  },

  switchTo: function(e) {
    var that = this;
    var id = e.target.id;
    if (this.data.currentTab == id) {
      return false;
    } else {
      that.setData({
        currentTab: id,
        active: id
      });
    }
  },

  // 添加swiper切换事件
  onSwiperChange: function(e) {
    const current = e.detail.current;
    this.setData({
      currentTab: current,
      active: current
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    that.getOnLine();
    that.getAllSensorsData();
    this.data.onLineInterval = setInterval(function() {
      that.getOnLine();
    }, 500);
    
    this.data.sensorsInterval = setInterval(function() {
      if (!that.data.isControlling) {
        that.getEnvironmentData(); 
      }
    }, 300);
  },

  getOnLine() {
    var that = this;
    wx.request({
      url: 'http://api.nlecloud.com/Devices/Status?devIds=1331841',
      method: "GET",
      header: {
        AccessToken
      },
      success: res => {
        if (res.data && res.data.ResultObj && res.data.ResultObj.length > 0) {
          const isOnline = res.data.ResultObj[0].IsOnline;
          
          if (!isOnline && that.data.tieleFlex == 0) {
            wx.showModal({
              title: '设备不在线',
              content: '请检查设备网络连接',
            })
            that.setData({
              tieleFlex: 1,
              titleFlex2: 0
            })
          }
          if (isOnline && that.data.titleFlex2 == 0) {
            wx.showToast({
              title: '设备在线',
              icon: 'success'
            })
            that.setData({
              tieleFlex: 0,
              titleFlex2: 1
            })
          }
          that.setData({
            onLine: isOnline,
          })
        }
      }
    })
  },
  getAllSensorsData() {
    var that = this;
    wx.request({
      url: 'http://api.nlecloud.com/Devices/Datas=?deviceId=1331841',
      method: "GET",
      header: {
        AccessToken
      },
      success: res => {
        if (res.data && res.data.ResultObj && res.data.ResultObj.Sensors) {
          const sensors = res.data.ResultObj.Sensors;
          that.setData({
            temp: sensors[0] ? sensors[0].Value : '',
            hum: sensors[1] ? sensors[1].Value : '',
            light: sensors[2] ? sensors[2].Value : '',
            temp_danwei: sensors[0] ? sensors[0].Unit : '',
            hum_danwei: sensors[1] ? sensors[1].Unit : '',
            light_danwei: sensors[2] ? sensors[2].Unit : '',
            fire: sensors[3] && sensors[3].Value == 1 ? "有火" : "没火",
            livingLightState: sensors[4] ? sensors[4].Value : 0,
            roomLightState: sensors[5] ? sensors[5].Value : 0,
            livingFanState: sensors[6] ? sensors[6].Value : 0,
            roomFanState: sensors[7] ? sensors[7].Value : 0,
            doorBig: sensors[8] ? sensors[8].Value : 0,
            doorCar: sensors[10] ? sensors[10].Value : 0,
            addressIP: res.data.ResultObj.LastOnlineIP || '',
            
            hasLoadedStaticData: true 
          })
        }
      },
      fail: err => {
        console.error('获取所有传感器数据失败:', err);
      }
    })
  },
  getEnvironmentData() {
    var that = this;
    wx.request({
      url: 'http://api.nlecloud.com/Devices/Datas=?deviceId=1331841',
      method: "GET",
      header: {
        AccessToken
      },
      success: res => {
        if (res.data && res.data.ResultObj && res.data.ResultObj.Sensors) {
          const sensors = res.data.ResultObj.Sensors;
          that.setData({
            temp: sensors[0] ? sensors[0].Value : '',
            hum: sensors[1] ? sensors[1].Value : '',
            light: sensors[2] ? sensors[2].Value : '',
            temp_danwei: sensors[0] ? sensors[0].Unit : '',
            hum_danwei: sensors[1] ? sensors[1].Unit : '',
            light_danwei: sensors[2] ? sensors[2].Unit : '',
            fire: sensors[3] && sensors[3].Value == 1 ? "有火" : "没火"
          })
        }
      },
      fail: err => {
        console.error('获取环境数据失败:', err);
      }
    })
  },
  controlDevice(apiTag, value, stateKey) {
    return new Promise((resolve, reject) => {
      if (stateKey) {
        const updateData = {};
        updateData[stateKey] = value;
        updateData.isControlling = true;
        this.setData(updateData);
      }

      wx.request({
        url: `http://api.nlecloud.com/Cmds?deviceId=1331841&apiTag=${apiTag}`,
        data: value,
        method: "POST",
        header: {
          AccessToken
        },
        success: res => {
          console.log(`控制成功: ${apiTag}=${value}`);
          setTimeout(() => {
            this.setData({
              isControlling: false
            });
          }, 3000);
          resolve(res);
        },
        fail: err => {
          console.error(`控制失败: ${apiTag}=${value}`, err);
          if (stateKey) {
            const updateData = {};
            updateData[stateKey] = value === 1 ? 0 : 1;
            updateData.isControlling = false;
            this.setData(updateData);
          }
          reject(err);
        }
      })
    });
  },

 // 电动推杆控制方法 - 点击开按钮时关按钮置零，反之亦然
controlDoor(apiTagOn, apiTagOff, targetState, stateKey) {
  return new Promise((resolve, reject) => {
    const currentState = this.data[stateKey];
    
    // 如果已经是目标状态，直接返回
    if (currentState === targetState) {
      console.log(`门已经是${targetState === 1 ? '开启' : '关闭'}状态`);
      return resolve();
    }

    // 设置控制锁定
    this.setData({ isControlling: true });

    // 核心逻辑：点击开按钮时将关按钮置零，点击关按钮时将开按钮置零
    // 1. 先将相反按钮置零（开->关置零，关->开置零）
    const oppositeApiTag = targetState === 1 ? apiTagOff : apiTagOn;
    console.log(`将${targetState === 1 ? '关' : '开'}按钮置零: ${oppositeApiTag}=0`);
    
    wx.request({
      url: `http://api.nlecloud.com/Cmds?deviceId=1331841&apiTag=${oppositeApiTag}`,
      data: 0,
      method: "POST",
      header: { AccessToken },
      success: () => {
        // 2. 延迟确保置零生效后，发送目标状态命令
        setTimeout(() => {
          const targetApiTag = targetState === 1 ? apiTagOn : apiTagOff;
          console.log(`发送${targetState === 1 ? '开' : '关'}门命令: ${targetApiTag}=1`);
          
          wx.request({
            url: `http://api.nlecloud.com/Cmds?deviceId=1331841&apiTag=${targetApiTag}`,
            data: 1,
            method: "POST",
            header: { AccessToken },
            success: (res) => {
              // 更新本地状态
              this.setData({
                [stateKey]: targetState,
                isControlling: false
              });
              console.log(`门控制成功: ${stateKey}=${targetState}`);
              wx.showToast({
                title: targetState === 1 ? '开门成功' : '关门成功',
                icon: 'success'
              });
              resolve(res);
            },
            fail: (err) => {
              console.error(`目标命令失败:`, err);
              this.setData({ isControlling: false });
              wx.showToast({ title: '控制失败', icon: 'error' });
              reject(err);
            }
          });
        }, 500);
      },
      fail: (err) => {
        console.error(`相反按钮置零失败:`, err);
        this.setData({ isControlling: false });
        wx.showToast({ title: '置零失败', icon: 'error' });
        reject(err);
      }
    });
  });
},

  // 灯光控制
  openLivingLight() {
    if (!this.data.onLine) return;
    this.controlDevice('m_lamp1', 1, 'livingLightState');
  },

  closeLivingLight() {
    if (!this.data.onLine) return;
    this.controlDevice('m_lamp1', 0, 'livingLightState');
  },

  openRoomLight() {
    if (!this.data.onLine) return;
    this.controlDevice('m_lamp2', 1, 'roomLightState');
  },

  closeRoomLight() {
    if (!this.data.onLine) return;
    this.controlDevice('m_lamp2', 0, 'roomLightState');
  },

  // 风扇控制
  openLivingFan() {
    if (!this.data.onLine) return;
    this.controlDevice('m_fan1', 1, 'livingFanState');
  },

  closeLivingFan() {
    if (!this.data.onLine) return;
    this.controlDevice('m_fan1', 0, 'livingFanState');
  },

  openRoomFan() {
    if (!this.data.onLine) return;
    this.controlDevice('m_fan2', 1, 'roomFanState');
  },

  closeRoomFan() {
    if (!this.data.onLine) return;
    this.controlDevice('m_fan2', 0, 'roomFanState');
  },

  // 门控制 - 使用新的电动推杆控制方法
  openBigDoor() {
    if (!this.data.onLine) return;
    this.controlDoor('dt1on', 'dt1off', 1, 'doorBig');
  },

  closeBigDoor() {
    if (!this.data.onLine) return;
    this.controlDoor('dt1on', 'dt1off', 0, 'doorBig');
  },

  openCarDoor() {
    if (!this.data.onLine) return;
    this.controlDoor('dt2on', 'dt2off', 1, 'doorCar');
  },

  closeCarDoor() {
    if (!this.data.onLine) return;
    this.controlDoor('dt2on', 'dt2off', 0, 'doorCar');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时重新获取静态数据（如果需要）
    if (!this.data.hasLoadedStaticData) {
      this.getAllSensorsData();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清理定时器
    if (this.data.onLineInterval) {
      clearInterval(this.data.onLineInterval);
    }
    if (this.data.sensorsInterval) {
      clearInterval(this.data.sensorsInterval);
    }
  },

  // 其他生命周期方法...
  onReady() {},
  onHide() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})